package com.ionehe.group.common.uaa.ex.application.rest;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ionehe.group.common.io.Response;
import com.ionehe.group.common.uaa.ex.application.converter.CustomerConverter;
import com.ionehe.group.common.uaa.ex.application.converter.FunctionVOConvert;
import com.ionehe.group.common.uaa.ex.application.model.CustomerInfoDeleteVO;
import com.ionehe.group.common.uaa.ex.application.model.CustomerInfoVO;
import com.ionehe.group.common.uaa.ex.application.model.FunctionVO;
import com.ionehe.group.common.uaa.ex.domain.service.CustomerReadService;
import com.ionehe.group.common.uaa.ex.domain.service.CustomerWriteService;
import com.ionehe.group.common.uaa.ex.domain.service.FunctionReadService;
import com.ionehe.group.common.uaa.ex.dto.CustomerInfoDTO;
import com.ionehe.group.common.uaa.ex.dto.CustomerInfoListDTO;
import com.ionehe.group.common.uaa.ex.dto.FunctionDTO;
import com.ionehe.group.common.uaa.ex.dto.Paging;
import com.ionehe.group.common.uaa.ex.dto.UserDetailDTO;
import com.ionehe.group.common.uaa.ex.dto.UserInfoDTO;
import com.ionehe.group.common.uaa.ex.enums.ErrorMessages;
import com.ionehe.group.common.uaa.ex.utils.DateUtil;
import com.ionehe.group.common.uaa.ex.utils.LoginUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Copyright (c) 2020 ionehe.com
 * Date: 2020/11/26 0026
 * Time: 14:39
 *
 * @author 2020年 <a href="mailto:a@ionehe.com">秀</a>
 */
@RestController
@RequestMapping("/api/uaa/customer")
@Api(value = "uaa-企业管理相关服务", tags = "uaa-企业管理相关服务")
public class UaaCustomerController {
    @Autowired
    CustomerWriteService customerWriteService;
    @Autowired
    CustomerReadService customerReadService;
    @Autowired
    CustomerConverter customerConverter;
    @Autowired
    FunctionReadService functionReadService;
    @Autowired
    LoginUtils loginUtils;

    @ApiOperation("修改或添加企业")
    @PostMapping("/addAndUpdate")
    public Response customerAddAndUpdate(@RequestBody CustomerInfoVO customerInfoVO) {
        Response<UserDetailDTO> res = loginUtils.getCurrentUser();
        if (res.success() && res.getData() != null) {
            UserInfoDTO user = res.getData().getUserInfoDTO();
            customerInfoVO.setPid(user.getCustomerId());
        }

        return customerWriteService.customerAddAndUpdate(customerConverter.vo2dto(customerInfoVO));
    }

    @ApiOperation("企业列表")
    @GetMapping("/list")
    public Response<Paging<CustomerInfoListDTO>> customerList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                              @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                              String type, String name,
                                                              String sortKey, String order,
                                                              String createTimeStart, String createTimeEnd,
                                                              String creditRating, String ratingTimeStart, String ratingTimeEnd) {
        if (StrUtil.isNotBlank(order) && !(order.equals("asc") || order.equals("desc"))) {
            return Response.no(ErrorMessages.ILLEGAL_PARAMS.toString());
        }
        Map<String, Object> conditions = new HashMap<>(5);

        Response<UserDetailDTO> res = loginUtils.getCurrentUser();
        if (!res.success()) {
            return Response.no(ErrorMessages.USER_NOT_LOGIN.toString());
        }

        UserDetailDTO userDetail = res.getData();
        if (userDetail != null && userDetail.getCustomerInfoDTO() != null) {
            CustomerInfoDTO customer = userDetail.getCustomerInfoDTO();
            Long id = customer.getId();
            String currType = customer.getType();
            // 平台管理端 根据type查相应的数据
            // 评级机构 根据自己id查
            if (StrUtil.equals(currType, "rating")) {
                conditions.put("pid", id);
                type = null;
            }
            // 银行端 查询type为ordinary_enterprise的数据
            if (StrUtil.equals(currType, "bank")) {
                conditions.put("type", "ordinary_enterprise");
                conditions.put("bank", "");
                type = null;
            }
        }


        if (type != null) {
            conditions.put("type", type);
        }
        if (StrUtil.isNotBlank(name)) {
            conditions.put("name", name);
        }
        if (StrUtil.isNotBlank(createTimeStart) && StrUtil.isNotBlank(createTimeEnd)) {
            conditions.put("createTimeStart", DateUtil.timestamp2Date(createTimeStart));
            conditions.put("createTimeEnd", DateUtil.timestamp2Date(createTimeEnd));
        }
        if (StrUtil.isNotBlank(creditRating)) {
            conditions.put("creditRating", creditRating);
        }
        if (StrUtil.isNotBlank(ratingTimeStart) && StrUtil.isNotBlank(ratingTimeEnd)) {
            conditions.put("ratingTimeStart", DateUtil.timestamp2Date(ratingTimeStart));
            conditions.put("ratingTimeEnd", DateUtil.timestamp2Date(ratingTimeEnd));
        }

        Response<Paging<CustomerInfoListDTO>> pagingRes = customerReadService.customerList(pageNum, pageSize, conditions, sortKey, order);

        if (!pagingRes.success() || pagingRes.getData() == null || pagingRes.getData().isEmpty()) {
            return pagingRes;
        }

        List<CustomerInfoListDTO> customerInfoListDTOList = pagingRes.getData().getData();

        // 补充授权信息
        if (userDetail != null && userDetail.getCustomerInfoDTO() != null) {
            CustomerInfoDTO customer = userDetail.getCustomerInfoDTO();
            Long id = customer.getId();
            if (StrUtil.equals(customer.getType(), "bank")) {
                customerInfoListDTOList.forEach(c -> {
                    c.setIsAuthorization(1);

                    Map<String, Object> extraMap = c.getExtraMap();
                    if (extraMap == null) {
                        c.setIsAuthorization(1);
                        return;
                    }
                    Object initiatedAuthorization = extraMap.get("initiatedAuthorization");
                    if (initiatedAuthorization == null) {
                        c.setIsAuthorization(1);
                        return;
                    }

                    List<Long> iaIds = JSONUtil.toList(JSONUtil.parseArray(JSONUtil.toJsonStr(initiatedAuthorization)), Long.class);
                    boolean isInitiatedAuthorization = iaIds.contains(id);
                    if (isInitiatedAuthorization) {
                        c.setIsAuthorization(0);
                    }
                });
            }
        }

        return pagingRes;
    }

    @ApiOperation("通过类型查询企业")
    @GetMapping("/listByType")
    public Response<List<CustomerInfoVO>> listByType(String type) {
        Response<List<CustomerInfoDTO>> res = customerReadService.listByType(type);
        if (!res.success()) {
            return Response.no("查询企业信息异常");
        }
        return Response.yes(customerConverter.dto2vo(res.getData()));
    }

    @ApiOperation("企业详情")
    @GetMapping("/detail")
    public Response<CustomerInfoVO> detail(Long id) {
        Response<CustomerInfoDTO> res = customerReadService.detail(id);
        if (!res.success()) {
            return Response.no(res.getMessage());
        }

        return Response.yes(customerConverter.dto2vo(res.getData()));
    }

    /**
     * 功能列表
     *
     * @return 套餐详情功能列表
     */
    @GetMapping("/SetMealDetailFunctionList")
    @ApiOperation("功能列表")
    public Response<List<FunctionVO>> functionDetailInfo(Long id) {
        Response<List<FunctionDTO>> res = functionReadService.setMealDetailFunctionList(id);
        if (!res.success()) {
            return Response.no(res.getMessage());
        }
        Response<List<FunctionVO>> yes = Response.yes(FunctionVOConvert.INSTANCE.dto2vo(res.getData()));
        yes.setMessage(null);
        return yes;
    }

    @ApiOperation("企业删除")
    @PostMapping("/delete")
    public Response<Boolean> customerDelete(@RequestBody @ApiParam("企业删除类") CustomerInfoDeleteVO customerInfoDeleteVO) {
        return customerWriteService.customerDelete(customerInfoDeleteVO.getId());
    }

}
